package com.hwg.emp.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hwg.emp.common.exception.EmpException;
import com.hwg.emp.model.RoleMD;
import com.hwg.emp.model.UserMD;
import com.hwg.emp.service.RoleService;
import com.hwg.emp.service.ServiceFactroy;
import com.hwg.emp.service.UserService;

public class LoginController extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// 1获取参数
		String account = req.getParameter("account");
		String password = req.getParameter("password");
		// 2调用业务层对象业务方法获取业务结果
		UserService service = ServiceFactroy.getService(UserService.class);
		RoleService roleService = ServiceFactroy.getService(RoleService.class);
		// 3进行页面跳转
		try {
			UserMD user = service.login(account, password);
			RoleMD role = roleService.getRoleByEmpId(user.getId());
			user.setRole(role);
			req.getSession().setAttribute("USER", user);
			resp.sendRedirect(req.getContextPath() + "/index.jsp");
			return;
		} catch (EmpException e) {
			req.setAttribute("message", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("message", "系统繁忙,请稍后再试!");
		}
		req.getRequestDispatcher("/login.jsp").forward(req, resp);

	}

}
